var ctxPath = '';
var hasFile = false; //是否有文件参数

$(document).ready(function () {
    var curUrl = location.href;
    var paramIdx = curUrl.indexOf('#');
    var $form = $("form");

    //回车事件
    $form.on("keyup", "input", function (e) {
        if (e.which === 13) {
            submitRequest();
        }
    });

    //返回对象展开/折叠事件
    $(".return-beans").on('click', '.return-beans-title', function () {
        $(this).next().toggle();
    });

    $.get(ctxPath + '/api/getFunction', {
        url: curUrl.substring(curUrl.indexOf("?url=") + 5, paramIdx > 0 ? paramIdx : curUrl.length)
    }, function (res) {
        var item = res.data;
        $("#url,#interface-url").text(item.url);
        $("#desc").text(item.desc);
        $("#request-type").text(item.requestType);

        var $form = $("#form");
        $form.data('action', item.url);
        $form.data('method', item.requestType);

        //参数
        var paramHtml = '';
        $.each(item.parameters, function (k, parameter) {
            var inputType = 'text';
            if (parameter.type.indexOf('File') > 0){
                inputType = 'file';
                hasFile = true;
            }
            var inputHtml = '<input type="' + inputType + '" name="' + parameter.name + '" value=""/>';
            paramHtml += '<div class="param ' + (parameter.required ? 'required' : 'optional') + '"><span class="code"><span class="codename">' + parameter.name + '</span> : <span class="type">' + parameter.type + '</span></span>' +
                ' - ' + parameter.desc + ' ' + inputHtml + '</div>'
        });
        $("#param-div").html(paramHtml);

        //返回值
        if (item.returnBeans){
            geneReturnBeans(item.returnBeans);
        }

        //如果地址栏有参数 则自动填充form
        if (paramIdx > 0 && curUrl.length > paramIdx + 1) {
            var params = curUrl.substring(paramIdx + 1);

            var paramArr = params.split("&");
            $.each(paramArr, function (k, param) {
                var arr = param.split("=");
                var name = arr[0];
                var value = arr[1];
                if (value !== '') {
                    $form.find("input[name=" + name + "]").val(value);
                }
            });
            submitRequest();
        }
        else {
            //如果没参数则提交
            if ($form.find("input[name]").length === 0) {
                submitRequest();
            }
        }
    });
});

function geneReturnBeans(returnBeans){
    var beanHtml = '';
    $.each(returnBeans, function (k, returnBean) {
        beanHtml += '<div><h5 class="return-beans-title"><a href="javascript:">'+returnBean.className+'</a></h5><div style="display: none">';

        $.each(returnBean.beanFields, function (l, beanField) {
            beanHtml += '<div class="param ' + (beanField.required ? 'required' : 'optional') + '"><span class="code"><span class="codename">' + beanField.name + '</span> : <span class="type">' + beanField.type + '</span></span>' +
                ' - ' + beanField.desc + '</div>'
        });

        beanHtml += '</div></div>';
    });
    $(".return-beans").html(beanHtml);
}

function submitRequest() {

    var $form = $("form");
    var $btn = $("#submit_button");
    var $div = $("#response-div");

    var isPass = true;
    $form.find(".param input").each(function () {
        var $this = $(this);
        var required = $this.parent().hasClass("required");
        var value = $this.val();

        if (required && value === '') {
            alert($this.attr("name") + "不能为空");
            isPass = false;
            return false;
        }
    });

    if (!isPass) {
        return;
    }

    $btn.prop("disabled", true);
    $btn.attr("value", "请求中...");
    $div.empty();
    var url = $form.data("action");

    if (!hasFile){
        var params = $form.serialize();
        $.ajax({
            url: ctxPath + url,
            type: $form.data("method"),
            traditional: true,
            data: params,
            //dataType: 'json',
            success: function (response) {
                $btn.prop("disabled", false);
                $btn.attr("value", "提交");
                $div.html(formatJson(response));
                location.href = ctxPath + "/api/function?url=" + url + "#" + params;
            },
            error: function (response) {
                $btn.prop("disabled", false);
                $btn.attr("value", "提交");
                alert(response.message || "服务器异常");
            }
        });
    } else {
        $form.attr("method", 'post');
        $form.ajaxSubmit({
            url: ctxPath + url,
            success: function (response) {
                console.log(response);
                $btn.prop("disabled", false);
                $btn.attr("value", "提交");
                $div.html(formatJson(response));
            }
        });
    }

}

//格式化代码函数
var formatJson = function (json, options) {
    var reg,
        formatted = '',
        pad = 0,
        PADDING = '    ';
    options = options || {};
    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true);
    options.spaceAfterColon = (options.spaceAfterColon !== false);
    if (typeof json !== 'string') {
        json = JSON.stringify(json);
    } else {
        json = JSON.parse(json);
        json = JSON.stringify(json);
    }
    reg = /([\{\}])/g;
    json = json.replace(reg, '\r\n$1\r\n');
    reg = /([\[\]])/g;
    json = json.replace(reg, '\r\n$1\r\n');
    reg = /(\,)/g;
    json = json.replace(reg, '$1\r\n');
    reg = /(\r\n\r\n)/g;
    json = json.replace(reg, '\r\n');
    reg = /\r\n\,/g;
    json = json.replace(reg, ',');
    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
        reg = /\:\r\n\{/g;
        json = json.replace(reg, ':{');
        reg = /\:\r\n\[/g;
        json = json.replace(reg, ':[');
    }
    if (options.spaceAfterColon) {
        reg = /\:/g;
        json = json.replace(reg, ':');
    }
    (json.split('\r\n')).forEach(function (node, index) {
            var i = 0,
                indent = 0,
                padding = '';

            if (node.match(/\{$/) || node.match(/\[$/)) {
                indent = 1;
            } else if (node.match(/\}/) || node.match(/\]/)) {
                if (pad !== 0) {
                    pad -= 1;
                }
            } else {
                indent = 0;
            }

            for (i = 0; i < pad; i++) {
                padding += PADDING;
            }

            formatted += padding + node + '\r\n';
            pad += indent;
        }
    );
    return formatted;
};